package com.stockz.equity.util;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.JpaTemplate;


public class CustomDatabaseEditor {
	
	
	public static void main(String args[]){
		String path = "spring-config.xml";
		ApplicationContext context = new ClassPathXmlApplicationContext(path);
		final JpaTemplate jpaTemplate = (JpaTemplate)context.getBean("jpaTemplate");
		
		Runtime.getRuntime().addShutdownHook(new Thread(){
			@Override
			public void run() {
				jpaTemplate.execute(new JpaCallback<Object>(){

					@Override
					public Object doInJpa(EntityManager em)
							throws PersistenceException {
						em.getTransaction().begin();
						em.flush();
						em.createNativeQuery("shutdown").executeUpdate();
						em.getTransaction().commit();
						return null;
					}
					
				});
			}
		});
		
		
		
		jpaTemplate.execute(new JpaCallback<Object>(){
			@Override
			public Object doInJpa(EntityManager em)
					throws PersistenceException {
				EntityTransaction transaction = em.getTransaction();
				transaction.begin();

				String sql = "update Configuration c set c.value = (select max(date) from Bar) where c.key = 'LAST_BSE_BREDTH_DOWNLOAD_DATE'";
				System.out.println(em.createQuery(sql).executeUpdate());
				
				//SYS_PK_10050
				//em.createNativeQuery("alter table public.scrip drop constraint SYS_PK_10050").executeUpdate();
				//em.createNativeQuery("drop index scripIndex_exchangeCode").executeUpdate();
				transaction.commit();
				return null;
			}
		});
	}
	
}
